let check_id = setInterval(async function () {

    let account = await session.get("account", null);
    let last_account = await session.get("last_account", null);

    let loading = await session.get("loading", false);
    let loading_time = await session.get("loading_time", 0);
    if (!!loading || new Date().getTime() - loading_time < 60000) {
        return;
    }

    let current_step = await session.get("current_step", null);
    let current_step_time = await session.get("current_step_time", 0);

    if (current_step == '_login') {
        window.clearInterval(check_id);
        await session.set("current_step_time", new Date().getTime());
        await login();
    }
    if (current_step == '_checkLogin' || (current_step == '_getAccountAndRefresh' && new Date().getTime() - current_step_time > 30000)) {
        window.clearInterval(check_id);
        await session.set("current_step", "_checkLogin");
        await session.set("current_step_time", new Date().getTime());
        await checkLogin();
    }

}, 2000)

async function checkLogin() {

    let loading = await session.get("loading", false);
    let loading_time = await session.get("loading_time", 0);
    if (!!loading || new Date().getTime() - loading_time < 60000) {
        return;
    }

    let account = await session.get("account", null);
    let last_account = await session.get("last_account", null);

    let checkCount = await session.get("check_" + account['username'], 0);
    await session.set("check_" + account['username'], checkCount + 1);


    let currentStep = await session.get("current_step", null);
    let current_step_time = await session.get("current_step_time", 0);
    if (currentStep == "_checkLogin") {
        if (window.location.href != 'https://www.cma-cgm.com/'
            && window.location.href != 'https://www.cma-cgm.com'
            && window.location.href.indexOf('auth.cma-cgm.com/as/authorization.oauth2') == -1) {
            window.location.href = 'https://www.cma-cgm.com/'
            return
        }

        let logout = $(".btn-deco").filter(function () {
            return this.innerHTML.indexOf("Log Out") != -1;
        });

        if (!!logout && logout.length > 0) {
            await session.set("login", true);
            console.log("已登陆" + account['username'])

            await session.set("current_step", "_get_remote_token");
            await session.set("current_step_time", new Date().getTime());

            let message = {"from": "extenstion", "action": "localStorage_get"};
            window.postMessage(message, "*");
            sendMsg({action: 'getCookie', domain: '.cma-cgm.com'})

            return;
        } else {
            console.log("未登录:" + account['username'])

            await session.remove("login");
            let last_step = await session.get("has_last_step");
            let hasLogin = await session.get("hasLogin", false);
            if (last_step == "getNewAccount") {
                await session.remove("has_last_step");
                await getNewAccount();
            } else if (last_step == '_login' || !hasLogin) {

                if (!!account['username']) {
                    let loginFailCount = await session.get(account['username'], 0);
                    if (loginFailCount > 0) {
                        await session.remove("has_last_step");
                        await session.remove(account['username']);
                        console.log("未登录: getNewAccount")

                        core.updateAccount(Object.assign(account, {
                            otherCache: null,
                            apiToken: null,
                            remark: "plugin_remark_error"
                        }))

                        await getNewAccount();
                        return;
                    } else {
                        await session.set(account['username'], loginFailCount + 1);
                        await session.remove("has_last_step");
                        await session.set("current_step", "_login");
                        await session.set("current_step_time", new Date().getTime());
                        console.log("未登录: reload")
                        window.location.reload();
                        return;
                    }
                }

            }
        }
    }
}

async function getNewAccount() {
    let account = await session.get("account", null);
    await session.remove("hasLogin");
    await session.set("last_account", account['username']);
    await session.remove("cookies");
    await session.remove("localStorage");
    await session.remove("current_step");
    console.log("重新获取账号2")
    await getAccountAndRefresh();
}

setInterval(async function () {
    let loading = await session.get("loading", false);
    let loading_time = await session.get("loading_time", 0);
    if (!!loading || new Date().getTime() - loading_time < 60000) {
        return;
    }

    let cookies = await session.get("cookies", null);
    let localStorage = await session.get("localStorage", null);
    let account = await session.get("account", null);
    let current_step = await session.get("current_step", null);
    let login = await session.get("login", false);
    let hasLogin = await session.get("hasLogin", false);
    let current_step_time = await session.get("current_step_time", 0);

    if (!!hasLogin && window.location.href.indexOf('auth.cma-cgm.com/as/authorization.oauth') == -1) {
        await session.remove("hasLogin");
    }

    if (!current_step) {
        return;
    }

    let __RequestVerificationToken = null;
    let eles = document.getElementsByName('__RequestVerificationToken');
    if (!!eles && eles.length > 0) {
        __RequestVerificationToken = eles[0].value;
    }

    if ((!!cookies && !!localStorage && !!account && !!__RequestVerificationToken && current_step == '_get_remote_token') || new Date().getTime() - current_step_time > 1000 * 120) {

        if (!cookies || !login) {
            return;
        }

        let bingoCount = await session.get("bingoCount", 0);
        if (bingoCount > 0) {
            await session.remove("bingoCount");
            let CookieStr = null;
            for (let cookie of cookies) {
                CookieStr += cookie.name + "=" + cookie.value + "; "
            }

            core.updateAccount(Object.assign(account, {
                otherCache: JSON.stringify({
                    localStorage: localStorage,
                    cookies: cookies
                }),
                apiToken: JSON.stringify({
                    __RequestVerificationToken: __RequestVerificationToken,
                    Cookie: CookieStr
                }),
                remark: !!login ? "" : "plugin_remark_error"
            }))

            await getNewAccount();
            return;
        } else {
            await session.set("bingoCount", bingoCount + 1);
            window.location.reload();
        }
    }
}, 1000)

async function login() {
    let loading = await session.get("loading", false);
    let loading_time = await session.get("loading_time", 0);
    if (!!loading || new Date().getTime() - loading_time < 60000) {
        return;
    }

    let currentStep = await session.get("current_step", null);
    let account = await session.get("account", null);
    let login = await session.get("login", false);

    if (currentStep == "_login" && !!account && !login) {
        console.log("to login - main:" + account['username'])
        if (window.location.href.indexOf('auth.cma-cgm.com/as/authorization.oauth') == -1) {
            $(".nav-link.mycma").filter(function () {
                return this.innerHTML.indexOf("My CMA CGM") != -1;
            }).get(0).click();
            await localTimeFunction(async function () {
                let btn = $(".btn.btn-secondary").filter(function () {
                    return this.innerHTML.indexOf("Log In") != -1;
                }).get(0);
                if (!!btn) {
                    btn.click();
                } else {
                    await session.set("login", true);
                    await session.set("current_step", "_checkLogin");
                    await session.set("current_step_time", new Date().getTime());
                    window.location.reload();
                    return;
                }
            }, 1000)
            return;
        }

        let hasLogin = await session.get("hasLogin", false)
        if (hasLogin) {
            return;
        }
        await session.set("hasLogin", true)

        let startTime = new Date().getTime()
        let waitInput_id = setInterval(async function () {
            let input_name = $("#login-email").get(0)
            if (!!input_name) {
                window.clearInterval(waitInput_id);
                let login = Array.from(document.getElementsByClassName("o-button primary")).filter(i => i.innerHTML.indexOf('Log in') != -1);
                if (login && login.length > 0) {
                    login[0].focus();
                    setTimeout(async function () {

                        document.getElementById("login-email").value = account['username']
                        let event = new InputEvent('input', {
                            'bubbles': true,		// 表示事件对象是否冒泡
                            'cancelable': true,	// 表示事件是否可以被取消，即能否用Event.preventDefault()取消这个事件。
                        });
                        document.getElementById("login-email").dispatchEvent(event);
                        document.getElementById("login-password").value = account['password']

                        event = new InputEvent('input', {
                            'bubbles': true,		// 表示事件对象是否冒泡
                            'cancelable': true,	// 表示事件是否可以被取消，即能否用Event.preventDefault()取消这个事件。
                        });
                        document.getElementById("login-password").dispatchEvent(event);

                        document.body.focus();

                        await session.set("current_step", "_checkLogin");
                        login[0].click();

                        console.log("登陆完成")
                    }, 3000);
                    return;
                }
            }
            if (new Date().getTime() - startTime > 100000) {
                window.clearInterval(waitInput_id)
            }
        }, 3000)
    }
}
